package com.gzhu.knowledgeAdmin.service.impl;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gzhu.knowledgeAdmin.common.exception.BusinessException;
import com.gzhu.knowledgeAdmin.common.handler.ScenceImportHandler;
import com.gzhu.knowledgeAdmin.common.result.ErrorCode;
import com.gzhu.knowledgeAdmin.common.utils.UserInfoUtils;
import com.gzhu.knowledgeAdmin.common.vo.KeywordExportVo;
import com.gzhu.knowledgeAdmin.common.vo.PageVo;
import com.gzhu.knowledgeAdmin.common.vo.SceneExportVo;
import com.gzhu.knowledgeAdmin.entity.Keyword;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


import com.gzhu.knowledgeAdmin.dao.SceneDao;
import com.gzhu.knowledgeAdmin.entity.Scene;
import com.gzhu.knowledgeAdmin.service.SceneService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;


@Service("sceneService")
public class SceneServiceImpl extends ServiceImpl<SceneDao, Scene> implements SceneService {

    @Override
    public PageVo queryPage(Map<String, Object> params) {
        // 获取当前页和每页大小
        long pageNo = Long.parseLong((String) params.get("page"));
        long pageSize = Long.parseLong((String) params.get("limit"));
        String keyWord = (String) params.get("keywords");

        Page<Scene> page = new Page<>(pageNo,pageSize);
        QueryWrapper<Scene> wrapper = new QueryWrapper<>();

        if (!StringUtils.isEmpty(keyWord)) {
            wrapper.like("name", keyWord);
        }
        // 只能查询自己公司的
        String gsid = UserInfoUtils.getCurrentUser().getGsid();
        wrapper.eq("gsid", gsid);

        baseMapper.selectPage(page,wrapper);

        return new PageVo(page);
    }

    @Override
    public void saveScene(Scene scene) {
        // 获取公司id
        String gsid = UserInfoUtils.getCurrentUser().getGsid();
        scene.setGsid(gsid);
        baseMapper.insert(scene);
    }

    @Override
    @Transactional
    public String importScene(MultipartFile file) throws IOException {
        ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
        String gsid = UserInfoUtils.getCurrentUser().getGsid();

        List<Scene> sceneList = reader.readAll(Scene.class);

        ScenceImportHandler scenceImportHandler = new ScenceImportHandler(gsid,sceneList);
        String msg = scenceImportHandler.handle();
        return msg;


    }

    @Override
    public void exportScene(Map<String, Object> params, HttpServletResponse response) {
        ExcelWriter writer = null;
        ServletOutputStream outputStream = null;

        try {
            // 查询需要导出的所有数据
            String keyWord = (String) params.get("keywords");
            QueryWrapper<SceneExportVo> wrapper = new QueryWrapper<>();

            if (!StringUtils.isEmpty(keyWord)) {
                wrapper.like("name", keyWord);
            }
            // 只能查询自己公司的
            String gsid = UserInfoUtils.getCurrentUser().getGsid();
            wrapper.eq("gsid", gsid);

            List<SceneExportVo> keywordList = baseMapper.selectExportList(wrapper);

            // 导出
            String fileName = "场景列表.xlsx";
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));

            //创建xlsx格式的
            writer = ExcelUtil.getWriter(true);

            // 一次性写出内容，使用默认样式，强制输出标题
            writer.write(keywordList, true);

            //out为OutputStream，需要写出到的目标流
            outputStream = response.getOutputStream();
            writer.flush(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭writer，释放内存
            writer.close();

            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 获取本公司所有场景
     * @return
     */
    @Override
    public List<Scene> getAll() {

        String gsid = UserInfoUtils.getCurrentUser().getGsid();

        QueryWrapper<Scene> wrapper = new QueryWrapper<>();
        wrapper.eq("gsid",gsid);

        return baseMapper.selectList(wrapper);
    }

}